<?php if (! class_exists ('Views')) die ('access denied') ?>
<?php
	$ID = XReq::FetchDrop ('id');
	$ID = $GLOBALS ['PG']->FetchValue ('select "Number" from "Invoices" where "Number" = %I;', $ID);
	if (! $ID) {
		HTML::E ('<p>No valid invoice id provided.</p>');
		return (FALSE);
	}

	if (XReq::FetchDrop ('delete-confirm')) { ?>
		<p>You are about to permanently delete the invoice <?php HTML::E ($ID) ?>.</p>
		<p class="warning">
			WARNING! There is no way to undo this action.
			Please confirm deletion only if you are absolutely sure you will never change your mind later.
		</p> <?php
		echo (modInvoices::Form ($ID));
		return (NULL);
	}

	$InvoiceTotal = 0;
	$Tables = array ('Calls' => 0, 'GPRS' => 0, 'SMS' => 0, 'MMS' => 0);
	$Owners = array ();
	foreach (array_keys ($Tables) as $Table) {
		$Totals = $GLOBALS ['PG']->FetchTable ('select "Owner", sum ("Cost") as "Total" from %L where "Invoice" = %I group by "Owner" order by "Owner";', $Table, $ID);
		foreach ($Totals as $Row) $Owners [$Row ['Owner']][$Table] = $Row ['Total'];
	}
?>
	<div id="nav"><a href="?Views[next]=">Admin pane</a></div>

	<h1>Invoice <?php HTML::E ($ID) ?></h1>

	<h2>Owners</h2>
	<table>
	<?php foreach ($Owners as $Owner => $OwnerTables) { $OwnerTotal = 0; ?>
		<tbody>
			<tr><th colspan="2"><?php echo $Owner ?></th></tr>
			<?php foreach ($OwnerTables as $Table => $Total) { $Tables [$Table] += $Total;  $OwnerTotal += $Total; ?>
				<tr><th><?php echo $Table ?></th><td><?php echo MoneyFormat ($Total) ?></td></tr>
			<?php } ?>
			<tr><th>Total</th><td><?php echo MoneyFormat ($OwnerTotal) ?></td></tr>
		</tbody>
	<?php } ?>
	</table>
	
	<h2>Totals</h2>
	<table>
		<?php foreach ($Tables as $Table => $Total) { $InvoiceTotal += $Total; ?>
			<tr><th><?php echo $Table ?></th><td><?php echo MoneyFormat ($Total) ?></td></tr>
		<?php } ?>
		<tr><th>Invoice grand total</th><td><?php echo MoneyFormat ($InvoiceTotal) ?></td></tr>
	</table>

	<h2>Note</h2>
	<p>This total may differ from what you see in the invoice original if there are numbers without details.</p>
	<p>You should also keep in mind that all these amounts do not include any taxes.</p>

	<form action="" method="get">
		<input type="hidden" name="Views[next]" value="invoice"/>
		<input type="hidden" name="Views[id]" value="<?php HTML::E ($ID) ?>"/>
		<button type="submit" name="Views[delete-confirm]" value="yes">Delete this invoice</button>
	</form>
